package com.heima.wemedia.service.impl;


import com.heima.feign.client.ScheduleFeignClient;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.utils.common.ProtostuffUtil;
import com.heima.wemedia.enums.TaskTypeEnum;
import com.heima.wemedia.service.WmNewsAutoScanService;
import com.heima.wemedia.service.WmNewsTaskService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * 专门用来调用延迟任务的接口
 */
@Service
public class WmNewsTaskServiceImpl implements WmNewsTaskService {

    @Autowired
    private ScheduleFeignClient scheduleFeginClient;

    @Autowired
    private WmNewsAutoScanService wmNewsAutoScanService;

    /**
     * 添加任务到延迟队列中
     *
     * @param id          文章的id
     * @param publishTime 发布的时间  可以做为任务的执行时间
     */
    @Override
    @Async//执行异步操作
    public void addNewsToTask(Integer id, Date publishTime) {

        //2.封装数据
        Task task=new Task();
        task.setPriority(TaskTypeEnum.NEWS_SCAN_TIME.getPriority());
        task.setTaskType(TaskTypeEnum.NEWS_SCAN_TIME.getTaskType());
        task.setExecuteTime(publishTime.getTime());//执行时间=发布时间
        WmNews wmNews=new WmNews();
        wmNews.setId(id);
        //序列化的时候必须是一个对象，不可以是普通类型
        task.setParameters(ProtostuffUtil.serialize(wmNews));
        //1.直接调用fegin接口
        scheduleFeginClient.addTask(task);
    }
    /**
     * 拉取任务
     */
    @Override
    @Scheduled(fixedRate = 50000)//每50s执行一次消费
    public void pollTask() {
        System.out.println("拉取任务开始执行了......");
        //1.调用feign接口
        int type=TaskTypeEnum.NEWS_SCAN_TIME.getTaskType();
        int priority=TaskTypeEnum.NEWS_SCAN_TIME.getPriority();
        Task task = scheduleFeginClient.poll(type, priority);
        if(task!=null){//不等于空就开始执行
            //2.调用自动审核业务的接口
            byte[] parameters = task.getParameters();
            //反序列化成wmnews对象
            WmNews wmNews = ProtostuffUtil.deserialize(parameters, WmNews.class);
            wmNewsAutoScanService.autoScanWmNews(wmNews.getId());
            System.out.println("拉取任务结束......");
        }

    }
}
